import cache from './cache.js';
let chronograph = {
	//计时器编号
	c: null,
	//记录计时
	minutes: '--',
	remainingSeconds: '--',
	timeTemp: 0,
	handoff: true,
	//计时时长(s)
	time() {
		return this.handoff ? cache.getTomato().work : cache.getTomato().rest;
	},
	//异步计时功能(番茄钟)开始按钮不能多次点击
	async chronographRuning() {
		uni.showToast({
			title: '开始专注',
			duration: 2000,
			icon: 'none'
		});
		//
		uni.getStorage({
			key: 'paused',
			success: (res) => {
				this.timeTemp = res.data;
			}
		});
		if (this.timeTemp === 0) {
			this.timeTemp = this.time();
		}
		//
		this.timeTemp = this.time();
		let temp = 10 //10秒
		this.c = setInterval(() => {
			if (this.timeTemp <= 0) {
				// clearInterval(this.c);
				this.handoff = !this.handoff;
				// uni.setStorageSync('buShow', false);
				this.stop();
				uni.vibrateLong();
			}
			//实时转换
			this.secondsToMinutes();
			this.timeTemp--;
			//5秒后开始检测
			temp--;
			if (temp === 0) {
				this.balance();
				this.setScreensavers();
			}
		}, 1000);
	},
	//暂停计时器
	paused() {
		//暂停缓存
		uni.setStorage({
			key: 'paused',
			data: this.timeTemp
		})
		clearInterval(this.c);
	},
	//终止计时器
	stop() {
		clearInterval(this.c);
		uni.removeStorage({
			key: 'paused'
		});
		this.minutes = '00'
		this.remainingSeconds = '00'
	},
	//时间转换器
	secondsToMinutes() {
		this.minutes = Math.floor(this.timeTemp / 60); // 取整数部分作为分钟数
		this.remainingSeconds = this.timeTemp % 60; // 取余数作为剩余的秒数
		if (this.minutes < 10) {
			this.minutes = '0' + this.minutes;
		}
		if (this.remainingSeconds < 10) {
			this.remainingSeconds = '0' + this.remainingSeconds;
		}
	},
	//获取屏保
	setScreensavers() {
		if (!uni.getStorageSync('Solid on') || !this.handoff) return;
		uni.navigateTo({
			url: '/pages/Screensavers/Screensavers'
		});
		uni.showToast({
			title: '暂停重新开始可跳转屏保',
			duration: 2000,
			icon: 'none'
		});
	},
	//获取陀螺仪
	balance() {
		if (!uni.getStorageSync('Screensavers') || !this.handoff) return;
		uni.onGyroscopeChange((res) => {
			if (res.x < -0.3 || res.x > 0.3) {
				uni.vibrateLong();
			}
		});
		uni.startGyroscope({
			interval: "normal",
			success() {
				console.log('success')
			},
			fail() {
				console.log('fail')
			}
		});
	},
	//关闭陀螺仪
	balanceStop() {
		uni.stopGyroscope({
			success() {
				console.log('stop success!')
			},
			fail() {
				console.log('stop fail!')
			}
		})
	}
}

export default chronograph;